import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { ProductService } from "../shared/product.service";

@Component ({
    selector : 'app-search',
    templateUrl : './search.component.html',
    styleUrls : ['./search.component.css']
})
export class SearchComponent implements OnInit {

    formModel : FormGroup;
    categorys : string[];

    constructor ( private productService : ProductService ) {
        let fb = new FormBuilder ();
        this.formModel = fb.group ({
            title : ['', Validators.minLength (3)],
            price : [null, this.postiviteNumValid],
            category : ['-1']
        });
    }

    postiviteNumValid ( control : FormControl ) : any {
        let price = parseInt (control.value);
        if ( !control.value ) {
            return null;
        }

        if ( price > 0 ) {
            return null;
        }
        else {
            return { postiviteNum : true }
        }
    }

    ngOnInit () {
        this.categorys = this.productService.getAllCate ();
    }

    onSerch () {
        if ( this.formModel.valid ) {
            console.info (this.formModel.value);
            this.productService.searchEvent.emit(this.formModel.value);
        }
    }

}
